package com.atguigu.yygh.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.common.util.JwtHelper;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.user.util.ConstantPropertiesUtil;
import com.atguigu.yygh.user.util.HttpClientUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

/**
 * @program: yygh_parent
 * @author: Mr.Zhuo
 * @create: 2022-03-15 09:48
 **/
@Controller
@RequestMapping("/api/user/wx")
public class WeiXiApiController {

    @Autowired
    private UserInfoService userInfoService;

    @ApiOperation("微信二维码生成器")
    @ResponseBody
    @GetMapping("getLoginParam")
    public R getLoginParam() {
        /*
        *    var obj = new WxLogin({
             self_redirect:true,
             id:"login_container",
             appid: "",
             scope: "",
             redirect_uri: "",
              state: "",
             style: "",
             href: ""
             });
        * */
        HashMap<String, Object> map = new HashMap<>();

        try {
            map.put("appid", ConstantPropertiesUtil.WX_OPEN_APP_ID);
            map.put("scope", "snsapi_login");
            String redirectUri = URLEncoder.encode(ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL, "utf-8");
            map.put("redirect_uri", redirectUri);
            map.put("state", System.currentTimeMillis() + "");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new YyghException(20001, "后台数据处理异常");
        }

        return R.ok().data(map);
    }

    @GetMapping("callback")
    public String callback(String code, String state, HttpSession session) {
        // 第二步：通过code获取access_token
        // https://api.weixin.qq.com/sns/oauth2/access_token?
        // appid=APPID
        // &secret=SECRET
        // &code=CODE
        // &grant_type=authorization_code
        HashMap<String, String> map = new HashMap<>();
        try {
            StringBuffer string = new StringBuffer()
                    .append("https://api.weixin.qq.com/sns/oauth2/access_token?")
                    .append("appid=%s")
                    .append("&secret=%s")
                    .append("&code=%s")
                    .append("&grant_type=%s");
            // 进行是数据填充
            String format = String.format(string.toString(),
                    ConstantPropertiesUtil.WX_OPEN_APP_ID,
                    ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                    code,
                    "authorization_code");
            String result = HttpClientUtils.get(format);

            // 然后通过数据转型进行获取数据
            JSONObject jsonObject = JSONObject.parseObject(result);
            String accessToken = jsonObject.getString("access_token");
            String openid = jsonObject.getString("openid");

            // 获取到数据之后我们需要判断当前用户是否之前注册过
            UserInfo userInfoDB = userInfoService.findUserInfoByOpenid(openid);

            if (StringUtils.isEmpty(userInfoDB)) {
                // 如果当前用户没有注册过，我们进行用户注册，获取用户信息
                StringBuffer buffer = new StringBuffer()
                        .append("https://api.weixin.qq.com/sns/userinfo?")
                        .append("access_token=%s")
                        .append("&openid=%s");
                String resultInfo = String.format(buffer.toString(), accessToken, openid);

                // 然后进行用户数据获取
                String s = HttpClientUtils.get(resultInfo);
                JSONObject jsonObjectInfo = JSONObject.parseObject(s);

                // 成功获取用户姓名之后我们进行数据保存
                userInfoDB = new UserInfo();
                userInfoDB.setOpenid(jsonObjectInfo.getString("openid"));
                userInfoDB.setNickName(jsonObjectInfo.getString("nickname"));
                userInfoDB.setStatus(1);

                // 数据持久化
                userInfoService.save(userInfoDB);
            }

            // 用户注册过 返回用户信息
            // 用户是否绑定过手机号
            String phone = userInfoDB.getPhone();
            if (StringUtils.isEmpty(phone)) {
                // 没有绑定过
                map.put("openid", userInfoDB.getOpenid());
            } else {
                // 绑定过
                map.put("openid", "");
            }
            String name = userInfoDB.getName();
            if (StringUtils.isEmpty(name)) {
                name = userInfoDB.getNickName();
            }
            if (StringUtils.isEmpty(name)) {
                name = userInfoDB.getPhone();
            }

            map.put("name", name);

            // 传输token值
            String token = JwtHelper.createToken(userInfoDB.getId(), name);
            map.put("token", token);

            // 最终重定向到前端页面
            return "redirect:http://localhost:3000/weixin/callback?token="
                    + map.get("token") + "&openid=" + map.get("openid") + "&name=" + URLEncoder.encode(map.get("name"), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
